package com.cscj.android.repository.network

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart



/**
 * 返回给UI层的数据结构
 */
sealed interface Result<out T> {



    data class Success<T>(val data: T) : Result<T>

    data class Error(val error: BusinessException) : Result<Nothing>{
        companion object{
            const val ERROR_BUSINESS = -100
        }
    }

    data class Loading<T>(val data: T? = null) : Result<T>
}

/**
 * copy from nio demo app.
 */
fun <T> Flow<T>.asResult(): Flow<Result<T>> {
    return this.map<T, Result<T>> {
        Result.Success(it)
    }.onStart {
        emit(Result.Loading())
    }.catch {
        emit(Result.Error(BusinessException(Result.Error.ERROR_BUSINESS, it.message)))
    }
}

